﻿'/*
' * Copyright ¸ 2005 Kele (fooleau@gmail.com)
' * This library is free software you can redistribute it and/or 
' * modify it under the terms of the GNU Lesser General Public 
' * License version 2.1 as published by the Free Software Foundation
' * (the "LGPL").
' * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
' * OF ANY KIND, either express or implied.
' */

imports System

Namespace Foole.Crypt
    '/ <summary>
    '/ This class handles the encryption that is done on the headers of world server packets.
    '/ The Key is 40 bytes long
    '/ </summary>
    Public Class WoWCrypt
        Private mInitialised As Boolean = False

        ' Encryption state
        Private mEncPrev As Byte
        Public mEncIndex As Integer

        ' Decryption state
        Public mDecPrev As Byte
        Public mDecIndex As Integer

        Public mKey As Byte()

        Public Sub Init(ByVal Key As Byte())
            mKey = Key.Clone()
            mInitialised = True
        End Sub

        Public Function GetDecPrev() As Byte
            Return mDecPrev
        End Function

        Public Sub SetDecPrev(ByVal SetTo As Byte)
            mDecPrev = SetTo
        End Sub

        Public Function GetDecIndex() As Integer
            Return mDecIndex
        End Function

        public sub SetDecIndex(SetTo As Integer)
            mDecIndex = SetTo
        End Sub

        Public Sub Decrypt(ByVal Data As Byte(), ByVal Length As Integer)
            If (mInitialised = False) Then Return

            For i = 0 To Length
				dim x as byte  = (byte)((Data[i] - mDecPrev) ^ mKey[mDecIndex])
				++mDecIndex
				mDecIndex %= mKey.Length
				mDecPrev = Data[i]
                Data([i] = x)
            Next
        End Sub

        Public Sub Encrypt(ByVal Data As Byte(), ByVal Length As Integer)
            If (mInitialised = False) Then Return

            For i = 0 To Length
				dim x as byte = (byte)((Data[i] ^ mKey[mEncIndex]) + mEncPrev)
				++mEncIndex
				mEncIndex %= mKey.Length
                mEncPrev = x
                Data([i] = x)
            Next
        End Sub
    End Class
End Namespace
